//
//  HRSoundCardCell.m
//  Hear
//
//  Created by mac on 2017/10/25.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRSoundCardCell.h"
#import "EaseBubbleView.h"
#import "HRCoverImageModel.h"
#import "Track.h"
#import "NSMutableAttributedString+GDAttString.h"
#import "HRDynamicCell.h"
#import "UIButton+SSEdgeInsets.h"
static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;
@interface HRSoundCardCell ()
{
    EMMessageBodyType _messageType;
    NSString *contentStr;
    Track *_track;
}
@property(nonatomic, strong)HRSoundButton *soundButton;

@end
@implementation HRSoundCardCell

+ (void)initialize{
    
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style
              reuseIdentifier:(NSString *)reuseIdentifier model:(id<IMessageModel>)model
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _messageType = model.bodyType;
        [self _setupSubviewsWithType:_messageType
                            isSender:model.isSender
                               model:model];
        
    }
    
    return self;
}

- (void)_setupSubviewsWithType:(EMMessageBodyType)messageType
                      isSender:(BOOL)isSender
                         model:(id<IMessageModel>)model{
    
    CGFloat pading = 10;
    
    _avatarView = [[UIImageView alloc] init];
    _avatarView.backgroundColor = [UIColor clearColor];
    _avatarView.clipsToBounds = YES;
    _avatarView.userInteractionEnabled = YES;
    [self.contentView addSubview:_avatarView];
    _avatarView.layer.cornerRadius = 20;
    _avatarView.clipsToBounds = YES;
    

    
    UIView *soundCardView = [UIView new];
    soundCardView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:soundCardView];
    
    
    UIView *topView = [UIView new];
    topView.backgroundColor = BlueColor;
    [soundCardView addSubview:topView];
    topView.layer.cornerRadius = 8;
    topView.clipsToBounds = YES;
    
    
    NSString *titleStr = @"Hi 我想认识你一下\n先听听我的留声机内容吧";
    UILabel *titleLabel = [UILabel new];
    titleLabel.attributedText = [NSMutableAttributedString arrtLabelText:titleStr arrFont:CustomUIFont(13) attColor:[UIColor whiteColor] lineLengh:5 alignment:1 colorLenghFrom:0 colorLengh:titleStr.length];
    titleLabel.font = CustomUIFont(13);
    titleLabel.textColor = [UIColor whiteColor];
    [topView  addSubview:titleLabel];
    titleLabel.numberOfLines = 2;
    titleLabel.textAlignment = 1;
    
    
    UIView *bottomView = [UIView new];
    bottomView.backgroundColor = [UIColor whiteColor];
    [soundCardView addSubview:bottomView];
    bottomView.layer.cornerRadius = 8;
    bottomView.clipsToBounds = YES;
    
    
    
    UILabel *topicTitle = [UILabel new];
    topicTitle.font = CustomUIFont(13);
    topicTitle.textColor = FirstTextColor;
    [bottomView  addSubview:(self.topicTitle=topicTitle)];
    topicTitle.numberOfLines = 0;
//    topicTitle.text = @"说说你坚持最久的一件事";
    topicTitle.textAlignment = 1;
    
    
    UIButton *ageButton = [UIButton buttonWithType:0];
//    [ageButton setTitle:@"90后" forState:0];
    [ageButton setTitleColor:SecondTextColor forState:0];
    ageButton.titleLabel.font = CustomUIFont(12);
    [ageButton addTarget:self action:@selector(ageButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:(self.ageButton=ageButton)];
//    [ageButton setImage:[UIImage imageNamed:@"nim_male"] forState:0];
    
    UILabel *distanceLabel = [UILabel new];
    distanceLabel.font = CustomUIFont(13);
    distanceLabel.textColor = SecondTextColor;
    [bottomView  addSubview:(self.distanceLabel=distanceLabel)];
//    distanceLabel.text = @"12km";
    
    self.soundButton = [HRSoundButton new];
    [self.soundButton setImage:[UIImage imageNamed:@"语音播放长条"] forState:0];
    [self.soundButton removeAllTargets];
    [self.soundButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.soundButton];
    
    if (isSender){
        _avatarView.frame = CGRectMake(kFullWidth-40-pading, pading, 40, 40);
        soundCardView.frame = CGRectMake(self.avatarView.left-pading*2-200, _avatarView.top, 200, 210);
    }else{
        _avatarView.frame = CGRectMake(pading, pading, 40, 40);
        soundCardView.frame = CGRectMake(self.avatarView.right+pading*2, _avatarView.top, 200, 210);
    }
    topView.frame = CGRectMake(0, 0, soundCardView.width, 80);
    titleLabel.frame = CGRectMake(pading, pading,soundCardView.width-pading*2, 40);
    bottomView.frame = CGRectMake(0, titleLabel.bottom+pading, soundCardView.width, soundCardView.height-titleLabel.bottom-pading);
    topicTitle.frame = CGRectMake(pading, pading*2, bottomView.width-pading*2, 40);

    ageButton.frame = CGRectMake(bottomView.width/2-60, topicTitle.bottom+pading, 60, 20);
    
    distanceLabel.frame = CGRectMake(bottomView.width/2, ageButton.top, bottomView.width, 20);
    
    self.soundButton.frame = CGRectMake(pading, distanceLabel.bottom+pading, bottomView.width-pading*2, 50);
    self.soundButton.leftImageView.frame = CGRectMake(15, 10, 13, 18);
    self.soundButton.voiceImageView.frame = CGRectMake(self.soundButton.leftImageView.right+10, 12, 20, 15);
    self.soundButton.voiceTimeLabel.frame = CGRectMake(self.soundButton.voiceImageView.right, -5, self.soundButton.width-self.soundButton.voiceImageView.right-15, self.soundButton.height);

    soundCardView.layer.shadowColor = [UIColor blackColor].CGColor;
    soundCardView.layer.shadowRadius      = 3;
    soundCardView.layer.shadowOpacity     = 0.2;
    soundCardView.layer.shadowOffset      = CGSizeMake(1, 1);
    soundCardView.layer.shadowPath        = [UIBezierPath bezierPathWithRect:soundCardView.bounds].CGPath;
    
    
    bottomView.layer.shadowColor = [UIColor blackColor].CGColor;
    bottomView.layer.shadowRadius      = 3;
    bottomView.layer.shadowOpacity     = 0.2;
    bottomView.layer.shadowOffset      = CGSizeMake(1, 1);
    bottomView.layer.shadowPath        = [UIBezierPath bezierPathWithRect:bottomView.bounds].CGPath;

    
}

- (void)looInfoTap{
    if (self.lookInfoBlock){
        self.lookInfoBlock();
    }
}

- (void)playButtonClick:(HRSoundButton *)button{
    _playBtnStatus = !_playBtnStatus;
    button.selected = !button.isSelected;
    
    if (_playBtnStatus) {
        [self createPlayer];

    }
    else {
        [self.streamer pause];
    }
    if (self.playCurrentCellBlock){
        self.playCurrentCellBlock();
    }
}


- (void)createPlayer{
    if (![_extDict[@"SoundUrl"] length]) return;
    
    Track *track = [[Track alloc] init];
    track.audioFileURL = [NSURL URLWithString:_extDict[@"SoundUrl"]];
    [self removeStreamerObserver];
    @try {
        [self removeStreamerObserver];
    } @catch(id anException){
    }


    _streamer = nil;
    _streamer = [DOUAudioStreamer streamerWithAudioFile:track];

    [self addStreamerObserver];
    [self.streamer play];

    DDLog(@"=====================创建了DOUAudioStreamer");
    
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    } else if (context == kDurationKVOKey) {
        //        [self performSelector:@selector(updateSliderValue:)
        //                     onThread:[NSThread mainThread]
        //                   withObject:nil
        //                waitUntilDone:NO];
    } else if (context == kBufferingRatioKVOKey) {
        //        [self performSelector:@selector(updateBufferingStatus)
        //                     onThread:[NSThread mainThread]
        //                   withObject:nil
        //                waitUntilDone:NO];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


- (void)updateStatus {
    //    self.musicIsPlaying = NO;
    //        _musicIndicator.state = NAKPlaybackIndicatorViewStateStopped;
    
    switch ([_streamer status]) {
        case DOUAudioStreamerPlaying:
            DDLog(@"=====================DOUAudioStreamerPlaying");
            [self.soundButton.voiceImageView startAnimating];
            break;
            
        case DOUAudioStreamerPaused:
            DDLog(@"=====================DOUAudioStreamerPaused");
            [self.soundButton.voiceImageView stopAnimating];
            break;
            
        case DOUAudioStreamerIdle:
            DDLog(@"=====================DOUAudioStreamerIdle");
            break;
            
        case DOUAudioStreamerFinished:
            DDLog(@"=====================DOUAudioStreamerFinished");
            [self.soundButton.voiceImageView stopAnimating];
            break;
            
        case DOUAudioStreamerBuffering:
            DDLog(@"=====================DOUAudioStreamerBuffering");
            [self.soundButton.voiceImageView stopAnimating];
            break;
            
        case DOUAudioStreamerError:
            DDLog(@"=====================DOUAudioStreamerError");
            [self.soundButton.voiceImageView stopAnimating];
            break;
    }
}

- (void)removeStreamerObserver {
    [_streamer removeObserver:self forKeyPath:@"status"];
    [_streamer removeObserver:self forKeyPath:@"duration"];
    [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
}

- (void)addStreamerObserver {
    [_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
    [_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
    [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
}



-(void)setExtDict:(NSDictionary *)extDict{
    _extDict = extDict;
    WeakSelf
    if (![extDict[@"FromLocalId"] isEqualToString:@"admin"]){
        [self.avatarView setImageWithURL:[NSURL URLWithString:extDict[@"UserPictureName"]] placeholder:[UIImage imageNamed:@""]];
    }
    
    
    self.topicTitle.text = extDict[@"QuestionText"];
    
    [self.ageButton setTitle:extDict[@"UserGroup"] forState:0];
    if ([extDict[@"Sex"] intValue]==1){
        [self.ageButton setImage:[UIImage imageNamed:@"nim_male"] forState:0];
    }else{
        [self.ageButton setImage:[UIImage imageNamed:@"nim_female"] forState:0];
    }
    [self.ageButton setImagePositionWithType:SSImagePositionTypeRight spacing:3];
    
    self.distanceLabel.text = extDict[@"DistanceText"];
    
    self.soundButton.voiceTimeLabel.text = [NSString stringWithFormat:@"%@S ", extDict[@"SoundLength"]];

}




#pragma mark - public

+ (NSString *)cellIdentifier
{
    return @"HRSoundCardCell";
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
